package com.ruoyi.spot.openapi.createNewOrder.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.spot.constants.SpotMonitorConstants;
import com.ruoyi.spot.openapi.createNewOrder.domain.VO.SpotOpenapiCreateNewOrderVO;
import com.ruoyi.util.SignUtil;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.spot.openapi.createNewOrder.service.ISpotOpenapiCreateNewOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 创建新订单Controller
 * 
 * @author saumell
 * @date 2024-08-13
 *
 *
 * 2024-8-17
 * 暂停开发，后续需要监控撮合的不同分片
 */
@RestController
@RequestMapping("/sp_api_creat_order/sp_api_creat_order_bak")
public class SpotOpenapiCreateNewOrderController extends BaseController
{
    @Autowired
    private ISpotOpenapiCreateNewOrderService spotOpenapiCreateNewOrderService;

    @Value("${my.lark.dangerlark}")
    private String dangerlark;

    @Value("${my.lark.recoverlark}")
    private String recoverlark;

    @Value("${my.secret.accesskey}")
    private String accesskey;

    @Value("${my.secret.secretkey}")
    private String secretkey;


    /**
     * 查询创建新订单列表
     */
    @PreAuthorize("@ss.hasPermi('sp_api_creat_order:sp_api_creat_order_bak:list')")
    @GetMapping("/list")
    public TableDataInfo list(SpotOpenapiCreateNewOrderVO spotOpenapiCreateNewOrder)
    {
        startPage();
        List<SpotOpenapiCreateNewOrderVO> list = spotOpenapiCreateNewOrderService.selectSpotOpenapiCreateNewOrderList(spotOpenapiCreateNewOrder);
        return getDataTable(list);
    }

    /**
     * 导出创建新订单列表
     */
    @PreAuthorize("@ss.hasPermi('sp_api_creat_order:sp_api_creat_order_bak:export')")
    @Log(title = "创建新订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SpotOpenapiCreateNewOrderVO spotOpenapiCreateNewOrder)
    {
        List<SpotOpenapiCreateNewOrderVO> list = spotOpenapiCreateNewOrderService.selectSpotOpenapiCreateNewOrderList(spotOpenapiCreateNewOrder);
        ExcelUtil<SpotOpenapiCreateNewOrderVO> util = new ExcelUtil<SpotOpenapiCreateNewOrderVO>(SpotOpenapiCreateNewOrderVO.class);
        util.exportExcel(response, list, "创建新订单数据");
    }

    private static String checkoutMessage(String openapiMessage) {
        // 解析返回值为 JSON 数组
        JSONArray jsonArray = JSON.parseArray(openapiMessage);
        return "true";
    }

    public void SpotOpenapiNewOrder() {
        List<SpotOpenapiCreateNewOrderVO> spotOpenAPIList = spotOpenapiCreateNewOrderService.selectSpotAllData();
        //新建放置需要报警、故障修复交易对的id
        List<Integer> dangerProductionInspections = new ArrayList<Integer>();
        List<Integer> recoverProductionInspections = new ArrayList<Integer>();
        for (SpotOpenapiCreateNewOrderVO spotOpenapiNewOrderVO : spotOpenAPIList) {
            Integer id = spotOpenapiNewOrderVO.getId();
            String currencyPair = spotOpenapiNewOrderVO.getCurrencyPair();
            String callingState = spotOpenapiNewOrderVO.getCallingState();
            Date lastExecutionTime = spotOpenapiNewOrderVO.getLastExecutionTime();
            Integer successTimes = spotOpenapiNewOrderVO.getSuccessTimes();
            Integer failTimes = spotOpenapiNewOrderVO.getFailTimes();
            Integer dangerWarning = spotOpenapiNewOrderVO.getDangerWarning();
            Integer safeWarning = spotOpenapiNewOrderVO.getSafeWarning();
            String openapirequest = null;
//            示例
            SignUtil signUtil = new SignUtil();
            String timemills = String.valueOf(System.currentTimeMillis());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            String bodymessage ="{\n" +
                    "    \"symbol\": \"btcusdt\",\n" +
                    "    \"volume\": 0.01,\n" +
                    "    \"side\": \"BUY\",\n" +
                    "    \"type\": \"MARKET\",\n" +
                    "    \"price\": 0,\n" +
                    "    \"newClientOrderId\": \"\"\n" +
                    "}";
            okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, bodymessage);
            String responsestring ;
            try {
            Request request = new Request.Builder()
                    .url(SpotMonitorConstants.SPOT_OPENAPI_ORDER)
                    .method("POST", body)
                    .addHeader("X-CH-APIKEY", accesskey)
                    .addHeader("X-CH-TS", timemills)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("X-CH-SIGN",signUtil.toSign(timemills,"POST",SpotMonitorConstants.SPOT_OPENAPI_ORDER_Url,"",bodymessage,secretkey))
                    .build();

                Response response = client.newCall(request).execute();
                responsestring = response.body().toString();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println(responsestring);

        }
    }
}
